<template>
	<view class="container">
		<scroll-view :scroll-into-view="itemview" scroll-x class="scroll-x" :scroll-left="scrollLeft"
			scroll-with-animation="true" @scroll="scrollMove">
			<view v-for="(item, index) in datalist" :key="index" class="view-parent">
				<view :id="'item'+index" @click="dianji(index)"
					:class="['view-item',currentIndex == index&&'scroll-item-active']" :data-index="index">
					<image :src="item.url" mode="aspectFill" class="bg-scroll"></image>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		name: "scroll-x",
		props: {
			datalist: {
				type: Array,
				default: () => ([])
			},
			currentIndex: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				scrollLeft: 0,
				itemview: 'item0',
				value: '',
			};
		},
		methods: {
			dianji(index) {
				this.getRect(`#item${index}`)
				this.$emit('select-index', index)
			},
			getRect(ele) {
				var that = this
				uni.createSelectorQuery().select(ele).boundingClientRect(function(rect) {
					// console.log(JSON.stringify(rect))
					//获取屏幕的宽度的一半
					var screen = uni.getSystemInfoSync().windowWidth / 2;
					// console.log('screen', screen)
					// console.log('rect', rect)
					//获取点击item的左边坐标
					var left = rect.left;
					//获取item的宽度de 一半
					var subhalfwidth = rect.width / 2
					//需要scrollview 移动的距离是
					var juli = left - screen
					// console.log('juli', juli)
					var zuizhongjuli = juli + subhalfwidth
					// console.log('zuizhongjuli', zuizhongjuli)
					this.scrollLeft = that.scrollLeft += zuizhongjuli
					// console.log('scrollLeft', this.scrollLeft)
				}).exec()
			},
			scrollMove(e) {
				// console.log(e)
				this.scrollLeft = e.detail.scrollLeft;
			},

		}
	}
</script>

<style lang="scss">
	.scroll-x {
		white-space: nowrap;
		height: 50px;
		position: relative;
		top: -50px;
		background: #FFFFFF80;
		backdrop-filter: blur(8px);
		padding-left: 10rpx;
	}

	.view-parent {
		display: inline-block;
		margin-top: 3px;
	}

	.view-item {
		width: 60px;
		height: 40px;
		margin-right: 10rpx;
		border-radius: 5px;
	}

	image {
		border-radius: 5px;
	}

	.bg-scroll {
		width: 100%;
		height: 100%;
	}

	.scroll-item-active {
		border: 4rpx solid red;
		border-radius: 5px;
	}
</style>